package com.chalmers.foa.gamehandlers.impl;

import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;

import android.util.Log;

import com.chalmers.foa.gamemodel.events.IEvent;
import com.chalmers.foa.gamemodel.events.impl.EventSwitch;
import com.chalmers.foa.gamemodel.gameobjects.other.impl.DoorIntent;
import com.chalmers.foa.gamemodel.gameobjects.other.impl.Enemy;
import com.chalmers.foa.gamemodel.level.ILevel;

public class EventHandler implements PropertyChangeListener {

	private static EventHandler instance;
	private PropertyChangeSupport pcs;
	private ILevel level;

	public static EventHandler getInstance() {
		if (instance == null)
			instance = new EventHandler();
		return instance;
	}

	private EventHandler() {
		pcs = new PropertyChangeSupport(this);
	}

	public void setLevel(ILevel _level) {
		level = _level;
	}

	@Override
	public void propertyChange(PropertyChangeEvent event) {
		if (level == null)
			return;
		if (event.getPropertyName().equals("enemyKilled"))
			enemyKilled((Enemy) event.getSource());
		else if (event.getPropertyName().equals("playerKilled")) {
			playerKilled();
		} else if (event.getPropertyName().equals("levelFinished")) {
			pcs.firePropertyChange(new PropertyChangeEvent(this, "NextLevel",
					null, null));
			
		}
		else if(event.getPropertyName().equals("startIntent")){
			pcs.firePropertyChange(new PropertyChangeEvent(this,
					"startIntent", null, event.getNewValue()));
		}
		else if (event.getPropertyName().equals("event")) {
			if (event.getNewValue() instanceof EventSwitch)
				((EventSwitch) (event.getNewValue())).switchActive();
		} else if (event.getPropertyName().equals("eventDelay")) {
			if (event.getNewValue() instanceof EventSwitch)
				((EventSwitch) (event.getNewValue()))
						.switchActiveAtTime((Integer) event.getNewValue());
		}
		else if(event.getPropertyName().equals("respawn")) {
			Log.v("Respawn 2","");
			((IEvent)(event.getNewValue())).switchActive();
		}
	}

	public void enemyKilled(Enemy enemy) {
		enemy.getParticleEffect().setPosition(enemy.getPosition());
		level.addParticles(enemy.getParticleEffect().getParticles());
	}

	public void playerKilled() {
		level.getPlayer().getParticleEffect().setPosition(
				level.getPlayer().getPlayerObject().getPosition());
		level
				.addParticles(level.getPlayer().getParticleEffect()
						.getParticles());
		pcs.firePropertyChange(new PropertyChangeEvent(this, "RestartLevel",
				null, null));
	}

	public void addPropertyChangeListener(PropertyChangeListener listener) {
		pcs.addPropertyChangeListener(listener);
	}
}
